import Vue from 'vue'
import Http from './modules/http'
import Table from './modules/table'
import Store from '../store'

Vue.mixin({
  mounted: function () {
    // 列表页
    this.setTableFilter()
  },
  methods: {
    ...Http,
    ...Table,
    // **************************************华丽的分割线*********************************************/
    getHost () {
      return process.env.API_HOST
    },
    toLogin () {
      const self = this
      const env = process.env.NODE_ENV
      if (env !== 'production') {
        location.hash = '/login'
      } else {
        self.$get('/api/security/info').then(res => {
          location.href = res.loginUrl
        })
      }
    },
    /**
     * param 将要转为URL参数字符串的对象
     * key URL参数字符串的前缀
     * encode true/false 是否进行URL编码,默认为true
     *
     * return URL参数字符串
     */
    parseParam (param, key, encode) {
      if (param == null) return ''
      var paramStr = ''
      var t = typeof (param)
      if (t === 'string' || t === 'number' || t === 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param)
      } else {
        for (var i in param) {
          var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
          paramStr += this.parseParam(param[i], k, encode)
        }
      }
      return paramStr
    },
    nativeTo (url, params = {}, target = '_blank') {
      if (!url.includes('http')) {
        url = this.getHost() + url
      }

      let A = document.createElement('A')
      const query = this.parseParam(params)
      A.setAttribute('href', `${url}?${query}`)
      A.setAttribute('target', target)
      A.click()
    },
    routerTo (routerName, query = {}, target = '_blank') {
      const {href} = this.$router.resolve({
        name: routerName,
        query: query
      })
      window.open(href, target)
    },
    goBack () {
      history.back()
    },
    authPower (powerId) {
      if (Utils.Object.toType(powerId) === 'array') {
        let auth = powerId.filter(power => Store.state.permission.includes(String(power)))
        return auth.length > 0
      }
      return Store.state.permission.includes(String(powerId))
    }
  }
})
